import React, { useState } from 'react';
import {
	Stack,
	FormControl,
	FormHelperText,
	InputGroup,
	InputLeftAddon,
	Input,
	Button,
	Text,
	Container,
	Flex,
	Divider,
	Center,
	Box,
	useToast,
  Spinner,
} from '@chakra-ui/react';
import { FaUserAlt, FaLock, FaCheck, FaMailBulk, FaWeixin, FaQq } from 'react-icons/fa';
import axios from 'axios';
import { Formik, Form, useFormik, Field, useField } from 'formik';
import * as Yup from 'yup';

function MyField({ ...props }) {
	const [ field, meta ] = useField(props);
	return <Input {...field} {...props} />;
}

const SignUp = () => {
  const toast = useToast();

  const [loading, setLoading] = useState(false)
  const [errors, setError] = useState({})

	const postSignUp = function(req) {
		// const req = {
		// 	user: {
		// 		username: 'Jacob',
		// 		email: 'jake@jake.jake',
		// 		password: 'jakejake'
		// 	}
		// };
    if (loading) return;
    setLoading(true)
    // https://conduit.productionready.io
		axios
			.post('https://api.realworld.io/api/users', { user: req })
			.then((res) => {
				console.log(res);
        setError({})
				toast({
          status: 'success',
          title: '注册成功',
          duration: 3000
        });
			})
			.catch((err) => {
				console.log(err);
        const errors = err.response.data.errors
        if (errors) {
          setError(errors)
        }
        toast({
          status: 'error',
          title: '注册失败',
          duration: 3000
        });
			}).finally(() => {
        setLoading(false)
      });
	};

	const formik = useFormik({
		initialValues: {
			username: '',
			email: '',
			password: ''
		},
		onSubmit: (values) => {
			postSignUp(values);
		}
	});
	// console.log(formik)

	const schema = Yup.object({
		username: Yup.string().max(15, '用户名的长度不能大于15').required('请输入用户名'),
		email: Yup.string().email('邮箱格式不正确').required('请输入邮箱'),
		password: Yup.string().min(6, '密码至少6位数').max(15, '密码最多15位数')
	});

	return (
    <>
    {loading ?
    <Center><Spinner
      thickness='4px'
      speed='0.65s'
      emptyColor='gray.200'
      color='blue.500'
      size='xl'
    /></Center>
    :
		<Formik initialValues={formik} onSubmit={formik.handleSubmit} validationSchema={schema}>
			<Form>
				<Stack spacing={4} pb="30px">
					<FormControl>
						<InputGroup borderRadius={0}>
							<InputLeftAddon children={<FaUserAlt />} />
							<Input
								placeholder="请输入用户名"
								name="username"
								value={formik.values.username}
								onChange={formik.handleChange}
							/>
						</InputGroup>
						{errors.username ? <FormHelperText color="red.400">{errors.username[0]}</FormHelperText> : null}
						<InputGroup borderRadius={0}>
							<InputLeftAddon children={<FaMailBulk />} />
							<Input
								placeholder="请输入邮箱"
								name="email"
								value={formik.values.email}
								onChange={formik.handleChange}
							/>
						</InputGroup>
            {errors.email ? <FormHelperText color="red.400">{errors.email[0]}</FormHelperText> : null}
						<InputGroup>
							<InputLeftAddon children={<FaLock />} />
							<Input
								type="password"
								placeholder="请输入密码"
								name="password"
								value={formik.values.password}
								onChange={formik.handleChange}
							/>
						</InputGroup>
						{/* <FormHelperText color="red.400">密码格式不正确</FormHelperText> */}
            {errors.password ? <FormHelperText color="red.400">{errors.password[0]}</FormHelperText> : null}
					</FormControl>
					<Button borderRadius="full" onClick={formik.handleSubmit}>
						注册
					</Button>
					<Container textAlign="center" fontSize="14px">
						<Text>点击“注册” 即表示您同意并愿意遵守简书</Text>
						<Flex justifyContent="center">
							<Text color="blue.300">用户协议</Text>
							<Text mx={1}>和</Text>
							<Text color="blue.300">隐私政策</Text>
						</Flex>
					</Container>
					<Center>
						<Divider />
						<Text wordBreak="keep-all" px={2} fontSize="14px">
							社交账号直接注册
						</Text>
						<Divider />
					</Center>
					<Center>
						<Box mx={4} color="green.400">
							<FaWeixin
								style={{
									width: '30px',
									height: '30px'
								}}
							/>
						</Box>
						<Box mx={4} color="blue.400">
							<FaQq
								style={{
									width: '30px',
									height: '30px'
								}}
							/>
						</Box>
					</Center>
				</Stack>
			</Form>
		</Formik>
    }
    </>
	);
};

export default SignUp;
